package com.assetmanage.service.impl;

import com.assetmanage.dao.BorrowDao;
import com.assetmanage.dao.impl.BorrowDaoImpl;
import com.assetmanage.model.Borrow;
import com.assetmanage.service.BorrowService;
import com.assetmanage.service.AssetService;

import java.util.Date;
import java.util.List;

public class BorrowServiceImpl implements BorrowService {
    private BorrowDao borrowDao = new BorrowDaoImpl();
    private AssetService assetService = new AssetServiceImpl();

    @Override
    public List<Borrow> getAllBorrows() {
        return borrowDao.getAllBorrows();
    }

    @Override
    public List<Borrow> getBorrowsByUser(int uId) {
        return borrowDao.getBorrowsByUser(uId);
    }

    @Override
    public List<Borrow> getBorrowsByAsset(String assetId) {
        return borrowDao.getBorrowsByAsset(assetId);
    }

    @Override
    public boolean addBorrow(Borrow borrow) {
        return borrowDao.addBorrow(borrow);
    }

    @Override
    public boolean updateBorrow(Borrow borrow) {
        return borrowDao.updateBorrow(borrow);
    }

    @Override
    public boolean deleteBorrow(int borrowId) {
        return borrowDao.deleteBorrow(borrowId);
    }

    @Override
    public Borrow getBorrowById(int borrowId) {
        return borrowDao.getBorrowById(borrowId);
    }

    @Override
    public boolean borrowAsset(int uId, String assetId, int num) {
        // 检查资产是否可借
        if (!assetService.checkAssetAvailable(assetId, num)) {
            return false;
        }

        // 创建借用记录
        Borrow borrow = new Borrow();
        borrow.setUId(uId);
        borrow.setAssetId(assetId);
        borrow.setBorrowStatus("已借出");
        borrow.setBorrowNum(num);

        return borrowDao.addBorrow(borrow);
    }

    @Override
    public boolean returnAsset(int borrowId) {
        Borrow borrow = getBorrowById(borrowId);
        if (borrow == null || !"已借出".equals(borrow.getBorrowStatus())) {
            return false;
        }

        borrow.setBorrowStatus("已归还");
        return borrowDao.updateBorrow(borrow);
    }

    @Override
    public boolean updateBorrowStatus(int borrowId, String status) {
        return borrowDao.updateBorrowStatus(borrowId, status);
    }

    @Override
    public List<Borrow> getUsageStats(Date startDate, Date endDate, String depId) {
        return borrowDao.getUsageStats(startDate, endDate, depId);
    }
} 